<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>观察者模式</title>
    <style>
        dt {
            font-size: 18px;
        }

        dd {
            font-size: 16px;
            color: cornflowerblue;
            font-weight: bold;
        }

        pre {
            background: #e9ecef;
            color: #000;
            padding: 20px;
        }
    </style>
</head>

<body>
    <dl>
        <dt>观察者模式定义：</dt>
        <dd>在软件设计中是一个对象，维护一个依赖列表，当任何状态发生改变自动通知它们。当一个对象被修改时，则会自动通知它的依赖对象。</dd>
    </dl>
    <dl>
        <dt>适用场景：</dt>
        <dd>1、DOM事件。</dd>
        <dd>2、vue双向绑定v-model</dd>
        <dd>3、学生与老师，学生类是被提问对象，老师是提问对象。</dd>
    </dl>
    <pre>
        <code>
       
            class Observer {
                constructor () {
                this.observerList = [];
                }
            
                subscribe (observer) {
                this.observerList.push(observer)
                }
            
                notifyAll (value) {
                this.observerList.forEach(observe => observe(value))
                }
            }
    </code>
    </pre>
    <script>
        class Observer {
            constructor() {
                this.observerList = [];
            }

            subscribe(observer) {
                this.observerList.push(observer)
            }

            notifyAll(value) {
                this.observerList.forEach(observe => observe(value))
            }
        }


        const observer = new Observer();
        observer.subscribe(value => {
            console.log("第一个观察者，接收到的值为:",value);
        });
        observer.subscribe(value => {
            console.log("第二个观察者，接收到的值为",value);
        });
        observer.notifyAll("通知哦")
    </script>
</body>

</html>